<template>
	<div class="chat-client-wrap">
		<div class="session-title">
			<span class="left-text">客户列表</span>
			<span class="mock-client-entry" @click="toMockPage">客户聊天入口</span>
		</div>
		<!--会话客户列表-->
		<div class="client-list">
			<div class="input-wrap">
				<h-icon name="search"></h-icon>
				<h-input placeholder="输入客户姓名查询" v-model="filterText" class="input-search"></h-input>
			</div>
			<div
				v-for="(item, index) of clientSortList" :key="index"
				v-show="item.isShow"
				class="client-item-wrap"
				:class="{active: currentClientId === item.customer_id}">
				<div class="client-item" @click="clientItemClick(item)">
					<div class="info-left">
						<img :src="item.gender === 'M' ? maleHeaderImg : femaleHeaderImg" class="header-img"/>
					</div>
					<div class="info-right">
						<div class="client-info">
							<div class="client-label">
								<span class="client-name ellipsis">{{item.real_name}}</span>
							</div>
							<div class="time">
								{{ handlerTime(item) }}
							</div>
						</div>
						<div v-if="item.last_message" class="session-question-wrap">
							<div class="session-question" v-html="item.last_message.message.content ? item.last_message.message.content : item.last_message.message.title"></div>
							<span v-show="item.un_read_count !== '0'" class="new-tag"></span>{{item.un_read_count !== '0' ? item.un_read_count : ''}}
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import femaleHeaderImg from '@/assets/images/female-round.png'
import maleHeaderImg from '@/assets/images/male-round.png'
import { mapState, mapMutations } from "vuex"
export default {
	name: 'ChatClientList',
	data() {
		return {
			femaleHeaderImg,
			maleHeaderImg,
			filterText: '',
			sessionIdMap: {}, // sessionid映射，用于做sessionid缓存,避免重复请求
			intervalTag: null,
			intervalDemandInfo: null
		}
	},
	computed: {
		...mapState('lm-chat', ['currentSessionInfo', 'clientList', 'currentClientId', 'currentClientInfo']),
		pathQuery() {
			return `?notNeedBack=true&clientId=${this.currentSessionInfo.client_id}&adviserName=${this.currentSessionInfo.adviser_name}&clientName=${this.currentSessionInfo.client_name}&sessionUuid=${this.currentSessionInfo.session_uuid}&adviserId=${this.currentSessionInfo.adviser_id}`
		},
		clientSortList() {
			if(!this.clientList.length) return []
			let tmpArr = this.clientList.map(u => {
				u.isShow = u.real_name.includes(this.filterText)
				return u
			})
			return tmpArr.sort((a, b) => {
				let bTime = b.last_message ? b.last_message.create_time : 0
				let aTime = a.last_message ? a.last_message.create_time : 0
				return bTime - aTime
			})
		}
	},
	created() {
		// 获取聊天客户列表
		this.queryCustomerList()
	},
	beforeDestroy() {
		if(this.intervalTag) {
			clearInterval(this.intervalTag)
		}
		if(this.intervalDemandInfo) {
			clearInterval(this.intervalDemandInfo)
		}
	},
	methods: {
		...mapMutations('lm-chat', [
			'seCurrentSessionInfo', 'setClientList', 'setClientDialogList', 'setClientLastMsgItem',
			'setScrollDialogMessage', 'setCurrentClientInfo', 'setGptMessageList', 'updateRecognitionModuleInfo', 'setCustomerDemandInfo', 'setHasCustomerDemand',
			'setClientDialogInput'
		]),
		// 时间展示处理
		handlerTime(item) {
			if(!item.last_message) {
				return ''
			}
			let timestamp = item.last_message.create_time
			 // 获取当前日期对象
			 const now = new Date();
			// 将给定时间戳转换为日期对象
			const givenDate = new Date(timestamp);
			// 获取当前日期（不含时间）
			const todayDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
			// 获取给定日期（不含时间）
			const givenDateOnly = new Date(givenDate.getFullYear(), givenDate.getMonth(), givenDate.getDate())
			// 比较日期
			if (todayDate.getTime() === givenDateOnly.getTime()) {
				return this.$public.dateFormat(timestamp, 'hh:mm')
			} else if (Math.abs(todayDate.getTime() - givenDateOnly.getTime()) === 86400000) { // 一天的毫秒数
				return '昨天'
			} else {
				return this.$public.dateFormat(timestamp, 'MM-dd')
			}
		},
		// 获取客户列表
		queryCustomerList() {
			this.$useGet(this.$url.queryLocalCustomerList, {
				agent_code: LOCAL_CONFIG.agent_code
			}).then(res => {
				let data = res.data
				let customerListAll = data.map(u => {
					if(!u.customer_id) {
						u.customer_id = u.customer_code
					}
					return u
				})
				// 重新组装一下客户列表数据
				// data.new_customer_list && data.new_customer_list.forEach(ele => {
				// 	customerListAll = customerListAll.concat(ele.customer_info_volist.map(u => {
				// 		// 如果customer_id不存在就取customer_code
				// 		if(!u.customer_id) {
				// 			u.customer_id = u.customer_code
				// 		}
				// 		return u
				// 	}))
				// })
				// data.old_customer_list && data.old_customer_list.forEach(ele => {
				// 	customerListAll = customerListAll.concat(ele.customer_info_volist.map(u => {
				// 		// 如果customer_id不存在就取customer_code
				// 		if(!u.customer_id) {
				// 			u.customer_id = u.customer_code
				// 		}
				// 		return u
				// 	}))
				// })
				let customerIdList = customerListAll.map(u => u.customer_id)
				// 根据代理人code和用户id集合查找列表session和最后的消息
				this.queryUserListSessionInfo(customerIdList, customerListAll)
			})
		},
		// 根据代理人code和用户id集合查找列表session和最后的消息
		queryUserListSessionInfo(customerIdList, customerListAll) {
			this.$usePost(this.$url.queryUserListSessionInfo, {
				user_ids: customerIdList,
				agent_code: LOCAL_CONFIG.agent_code,
				user_type: "1"
			}).then(res => {
				let lasMsgItemList = res.data
				lasMsgItemList.forEach(ele => {
					customerListAll.forEach(item => {
						if (ele.user_id == item.customer_id) {
							item = Object.assign(item, ele)
						}
					})
				})
				// 设置客户列表数据
				this.setClientList(customerListAll)
				// 设置当前客户信息
				this.setCurrentClientInfo(this.clientSortList[0])
				// 设置客户id对应的对话列表
				// this.clientList.forEach(element => {
				// 	this.setClientDialogInfoMap({
				// 		clientId: element.customer_id,
				// 		dialogMessageList: []
				// 	})
				// })
				// 获取对话session信息
				this.getSessionInfo()
			})
		},
		// 获取对话session信息
		getSessionInfo() {
			if(this.sessionIdMap[this.currentClientId]) {
				this.seCurrentSessionInfo(this.sessionIdMap[this.currentClientId])
				this.getSessionInfoCallBack()
				return
			}
			this.$usePost(this.$url.getSessionInfo, {
				user_id: this.currentClientId,
				agent_code: LOCAL_CONFIG.agent_code
			}).then(res => {
				let data = res.data
				this.sessionIdMap[this.currentClientId] = data
				this.seCurrentSessionInfo(data)
				this.getSessionInfoCallBack()
			})
		},
		// 获取对话session信息后续处理
		getSessionInfoCallBack() {
			this.updateSessionReaded()
			this.getHistoryMessage('1')
			this.getHistoryMessage('2')
			this.getEmotionAndOther()
			this.allIntentions()
			this.getAdviceTag()
			this.getCustomerDemandInfo()
			this.getHasCustomerDemand()
			if(this.intervalTag) {
				clearInterval(this.intervalTag)
			}
			if(this.intervalDemandInfo) {
				clearInterval(this.intervalDemandInfo)
			}
			this.intervalTag = setInterval(() => {
				this.getAdviceTag()
				this.allIntentions()
			}, 3000)
			this.intervalDemandInfo = setInterval(() => {
				this.getCustomerDemandInfo()
			}, 5000)
		},
		// 更新会话中的用户消息为已读
		updateSessionReaded() {
			this.$usePost(this.$url.updateSessionReaded, {
				session_id: this.currentSessionInfo.session_id
			}).then(res => {
				this.setClientLastMsgItem({
					clientId: this.currentClientId,
					isUpdateUnReadCount: true
				})
			})
		},
		// 查询识别模块信息
		getEmotionAndOther() {
			this.$usePost(this.$url.getEmotionAndOther, {
				session_id: this.currentSessionInfo.session_id
			}).then(res => {
				let data = res.data
				// this.setRecognitionModuleInfo({
				// 	emotionInfo: {
				// 		emotion: data.emotion,
        // 		emotion_item: data.emotion_item
				// 	}, // 情绪
				// 	clientTag: [], // 客户标签
				// 	clientIntent: [], // 客户意图
				// })
				this.updateRecognitionModuleInfo({
					moduleName: 'emotionInfo',
					moduleData: {
						emotion: data.emotion,
						emotion_item: data.emotion_item
					}
				})
			})
		},
		// 查询识别模块客户标签
		getAdviceTag() {
			this.$usePost(this.$url.getAdviceTag, {
				session_id: this.currentSessionInfo.session_id,
				user_id: this.currentClientId
			}, false).then(res => {
				let data = res.data
				this.updateRecognitionModuleInfo({
					moduleName: 'clientTag',
					moduleData: data
				})
			})
		},
		// 查询识别模块信息
		allIntentions() {
			this.$usePost(this.$url.allIntentions, {
				user_id: this.currentClientId
			}, false).then(res => {
				let data = res.data
				this.updateRecognitionModuleInfo({
					moduleName: 'clientIntent',
					moduleData: data || []
				})
			})
		},
		// 获取客户保障检视最新结果
		getCustomerDemandInfo() {
			this.$usePost(this.$url.getCustomerDemandInfo, {
				customer_id: this.currentClientId,
			}, false).then(res => {
				this.setCustomerDemandInfo(res.data)
			})
		},
		// 获取客户是否已投保
		getHasCustomerDemand() {
			this.$usePost(this.$url.getHasCustomerDemand, {
				customer_id: this.currentClientId,
			}, false).then(res => {
				this.setHasCustomerDemand(res.data)
			})
		},
		// 根据sessionId查询会话中的所有消息
		getHistoryMessage(userType) {
			this.$usePost(this.$url.getHistoryMessage, {
				session_id: this.currentSessionInfo.session_id,
				user_type: userType,    // 1.查询用户和代理人的消息 2.查询代理人和ai的消息
				// current: 1, // 缺省时查最后一页数据
				size: 100
			}).then(res => {
				if(userType === '1') {
					let messageList = res.data.records.filter(u => u.message_type === '1' || u.message_type === '2')
					// this.setClientDialogInfoMap({
					// 	clientId: this.currentClientId,
					// 	dialogMessageList: messageList
					// })
					this.setClientDialogList(messageList)
					// this.$nextTick(() => {
					// 	this.setScrollDialogMessage(true)
					// })
					setTimeout(() => {
						this.setScrollDialogMessage(true)
					}, 300)
				} else {
					let messageList = res.data.records.filter(u => u.message_type === '3' || u.message_type === '4')
					this.setGptMessageList(messageList)
				}
			})
		},
		// 点击切换聊天客户
		clientItemClick(item) {
			this.setCurrentClientInfo(item)
			this.getSessionInfo()
			this.setClientDialogInput('')
		},
		// 跳到模拟页面
		toMockPage() {
			let pageObj = {
				uuid: 'MobileDialog', // 必填项， 页签唯一 Id
				url: '/mobile-dialog', // 页签跳转链接
				title: '移动端模拟页面', // 页签显示的 title
				tab_ext_field: {
					parentId: 'ImChat',
					activeTabId: 'ImChat'
				},
				query: {
					client_id: this.currentClientId,
					client_name: this.currentClientInfo.real_name,
					session_id: this.currentSessionInfo.session_id,
				},
				// originData: {
				// 	is_keep_alivea: true,
				// 	id: 'MobileDialog'
				// }
			}
			this.$navigateFun(pageObj)
			// let str = `?client_id=${this.currentClientId}&client_name=${this.currentClientInfo.real_name}&session_id=${this.currentSessionInfo.session_id}`
			// window.open('/frame-layout/chat-aia/#/mobile-dialog' + str, '_blank')
		},
	}
}
</script>

<style lang="scss" scoped>
.chat-client-wrap{
	width: 260px;
	background: #F7F7F7;
	border-radius: 8px;
	position:absolute;
	top: 20px;
	right: 16px;
	bottom: 0px;
}
.session-title{
	padding: 14px 12px 14px 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.left-text{
		font-weight: bold;
		font-size: 18px;
		color: #172323;
	}
	.mock-client-entry{
		cursor: pointer;
		display: inline-block;
		height: 28px;
		line-height: 28px;
		padding: 0 10px;
		background: #EAEAEA;
		border-radius: 4px;
		color: #464646;
	}
}
.client-list{
	height: calc(100% - 56px);
	overflow: hidden auto;
	overflow-y: overlay;
	padding: 10px;
	.input-wrap{
		position:relative;
		padding-bottom: 16px;
		/deep/ .icon-search{
			position: absolute;
			left: 8px;
			top: 2px;
			z-index: 1;
			color: #999;
		}
		.input-search{
			/deep/ .h-input{
				padding-left: 28px;
			}
		}
	}
	.client-item-wrap{
		padding: 6px 0;
		&.active{
			.client-item{
				background: #EEF2F8;
			}
		}
		.client-item{
			line-height: 1;
			border-radius: 4px;
			cursor: pointer;
			position: relative;
			padding: 10px;
			color: #B1B1B1;
			display: flex;
			.info-left{
				width: 36px;
				height: 36px;
				margin-right: 10px;
				overflow: hidden;
				flex-shrink: 0;
				.header-img{
					width:100%;
				}
			}
			.info-right{
				flex: 1;
				width: 0;
				.client-info{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.client-label {
						display: flex;
						align-items: center;
						.client-name{
							font-size: 14px;
							font-weight: 700;
							word-break: break-all;
							color: #464646;
							max-width: 77px;
						}
						.mobile-img{
							width: 18px;
							height: 18px;
							margin-left: 8px;
						}
					}
				}
			}
			.session-question-wrap{
				display:flex;
				align-items: center;
				margin-top: 8px;
				.session-question{
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					word-break: break-all;
					flex: 1;
					/deep/ *{
						color: #B1B1B1 !important;
						background-color: unset !important;
					}
				}
				.new-tag{
					display: inline-block;
					width: 6px;
					height: 6px;
					border-radius: 100%;
					background: #D72323;
				}
			}
		}
	}
}
</style>